<template>
  <ElFormItem
    :label="titleText(options, item)"
    :prop="[childIndex, 'value']"
    :rules="{
      required: item.isRequired === 'Y',
      message: '请选择',
      trigger: 'change',
    }"
    class="flex_column"
  >
    <p v-if="options.showDesc" class="desc f12 mb10">
      {{ options.description }}
    </p>
    <div class="slider_box">
      <div v-for="(next, idx) in options.optionItems" :key="idx" class="m15">
        <p v-if="options.optionItems.length > 1" class="mb10">
          {{ next.label }}
        </p>
        <Slider
          v-model="item.value[idx]"
          :disabled="type === 'view'"
          :max="max"
          :min="min"
          @change="onChange(idx)"
        >
          <template #button>
            <div class="custom-button">
              {{
                item.value[idx] ||
                (options.sliderSet.limitValue ? options.sliderSet.min : 0)
              }}
            </div>
          </template>
        </Slider>
        <p class="flb">
          <span class="f12">{{ options.sliderSet.minText }}</span
          ><span class="f12">{{ options.sliderSet.maxText }}</span>
        </p>
      </div>
    </div>
  </ElFormItem>
</template>

<script setup>
import { titleText } from "@/utils/common.js";
import { ElFormItem, ElMessage } from "element-plus";
import { Slider } from "vant";
import { onBeforeMount, onMounted, ref } from "vue";

//defineOptions({ name: "GHSlider" });

const { item, type, index, childIndex } = defineProps([
  "item",
  "type",
  "index",
  "childIndex",
]);
const emits = defineEmits(["change"]);
const { options } = JSON.parse(item.vformJson);
let min = ref(0);
let max = ref(100);
// 传递值改变后
const onChange = (idx) => {
  let sum = eval(item.value.join("+"));
  if (options.sliderSet.limitTotal && sum > options.sliderSet.total) {
    ElMessage.error("总和不能超过" + options.sliderSet.total);
    item.value[idx] = 0;
  }
  emits("change", item);
};

onBeforeMount(() => {
  if (!item.value) {
    item.value = [];
  }
});
// 添加校验进入form
// const refFormItem = ref()
// const addField = inject('addField')
// 挂载后运行
onMounted(() => {
  // item.isRequired === 'Y' && addField(refFormItem.value)
  if (options.sliderSet.limitValue) {
    min.value = options.sliderSet.min || 0;
    max.value = options.sliderSet.max || 100;
  }
  let sum = eval(item.value.join("+"));
  if (!sum) item.value = options.optionItems.map(() => 0); // 填写的时候
});
</script>

<style lang="less" scoped>
.custom-button {
  width: 26px;
  color: #fff;
  font-size: 10px;
  line-height: 18px;
  text-align: center;
  background-color: var(--van-primary-color);
  border-radius: 100px;
}

.slider_box {
  flex: 1;
  width: 80%;
}
</style>